package com.seek.inter;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.seek.common.handler.SpringContextHolder;
import com.seek.model.dto.ResultInfo;
import com.seek.service.LoanService;
import com.seek.service.ReadService;
import com.seek.util.CommonUtil;

/**
 * 货款订单手工放款相关接口
 *
 */
public class LoanHandDownInter {
	
	private LoanService loanService = (LoanService)SpringContextHolder.getBean("loanService");
	private ReadService readService = (ReadService)SpringContextHolder.getBean("readService");
	
	/**
	 * 获取等待下款列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getLoanDownList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		int downType = CommonUtil.getIntValue(reqJson.getLong("downType"));
		int downStatus = CommonUtil.getIntValue(reqJson.getInteger("downStatus"));		
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and b.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and a.start_time > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and a.start_time < ?");
			params.add(rqz);
		}
		if (downType > 0){
			where.append(" and a.down_type= ?");
			params.add(downType);
		}
		if (downStatus > 0){
			if (downStatus == 1)
				where.append(" and a.loan_status=2");
			else if (downStatus==2){
				where.append(" and a.loan_status in (3,5,6)");
			}else{
				where.append(" and a.loan_status=4");
			}
		}else{
			where.append(" and a.loan_status>1");
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a, t_customer b, t_customer_card c where c.history=0 and a.customer_id=b.id and b.id=c.customer_id and a.company_id=?"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb.append("select a.id loanId,REPLACE(b.phone_no, SUBSTR(b.phone_no,4,4), '****') custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,a.end_time endTime,a.down_money downMoney,");
		else
			sb.append("select a.id loanId,b.phone_no custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,a.end_time endTime,a.down_money downMoney,");
		sb.append(" a.req_date reqTime,a.loan_status loanStatus,a.down_type downType,a.down_remark downRemark,c.bank_name bankName, ")
		.append(" c.card_number cardNumber,a.down_time downTime,a.down_img downImg,b.id custId")
		.append(" from t_loan a, t_customer b, t_customer_card c")
		.append(" where c.history=0 and a.customer_id=b.id and b.id=c.customer_id and a.company_id=?");
		sb.append(where).append(" order by a.id asc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}

	/**
	 * 获取连连放款对账列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getLoanBlanaceList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		String custPhone = reqJson.getString("custPhone");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		int downType = CommonUtil.getIntValue(reqJson.getLong("downType"));
		int downStatus = CommonUtil.getIntValue(reqJson.getInteger("downStatus"));
		int loanType = CommonUtil.getIntValue(reqJson.getInteger("loanType"));

		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and b.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and a.down_time > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and a.down_time < ?");
			params.add(rqz);
		}
		if (downType > 0){
			where.append(" and a.down_type= ?");
			params.add(downType);
		}
		if (downStatus > 0){
			if (downStatus == 1)
				where.append(" and a.loan_status=2");
			else if (downStatus==2){
				where.append(" and a.loan_status in (3,5,6)");
			}else{
				where.append(" and a.loan_status=4");
			}
		}else{
			where.append(" and a.loan_status>2");
		}
		if (loanType > 0) {
			where.append(" and a.loan_type= ?");
			params.add(loanType);
		}

		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a, t_customer b, t_customer_card c where c.history=0 and a.customer_id=b.id and b.id=c.customer_id and a.company_id=?"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb.append("select a.id loanId,REPLACE(b.phone_no, SUBSTR(b.phone_no,4,4), '****') custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,a.end_time endTime,a.down_money downMoney,");
		else
			sb.append("select a.id loanId,b.phone_no custPhone,b.name custName,a.req_money reqMoney,a.start_time startTime,a.end_time endTime,a.down_money downMoney,");
		sb.append(" a.req_date reqTime,a.loan_type loanType ,a.loan_status loanStatus,a.down_type downType,a.down_remark downRemark,c.bank_name bankName, ")
				.append(" c.card_number cardNumber,a.down_time downTime,a.down_img downImg,b.id custId")
				.append(" from t_loan a, t_customer b, t_customer_card c")
				.append(" where c.history=0 and a.customer_id=b.id and b.id=c.customer_id and a.company_id=? ");
		sb.append(where).append(" order by a.id asc");

		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}


	/**
	 * 手工放款
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo uploadDownImg(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long loanId = reqJson.getLong("loanId");
		String creditImg = reqJson.getString("creditImg");	
		String userId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || loanId==null || loanId<1 || CommonUtil.isEmpty(creditImg)) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		} 
		
		loanService.loanHandDown(userId, creditImg, companyId, loanId);
				
		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}
	
	/**
	 * 获取货款待审核列表
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo getUserLoanAuditList(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long userId = reqJson.getLong("userId");
		String custPhone = reqJson.getString("custPhone");
		String rqq = reqJson.getString("rqq");
		String rqz = reqJson.getString("rqz");
		Integer auditStatus = reqJson.getInteger("auditStatus");
		if (userId == null || userId < 1 || companyId == null || companyId<1){
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		}
		
		// 拼接检索条件
		StringBuffer where = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		params.add(companyId);
		params.add(userId);
		if (!CommonUtil.isEmpty(custPhone)){
			custPhone = "%"+custPhone+"%";
			where.append(" and b.phone_no like ?");
			params.add(custPhone);
		}
		if (!CommonUtil.isEmpty(rqq)){
			where.append(" and a.req_date > ?");
			params.add(rqq);
		}
		if (!CommonUtil.isEmpty(rqz)){
			rqz = rqz.substring(0,10)+" 23:59:59";
			where.append(" and a.req_date < ?");
			params.add(rqz);
		}
		if (auditStatus != null && auditStatus > 0){
			if (auditStatus <= 1)
				where.append(" and a.loan_status= ?");
			else
				where.append(" and a.loan_status>=?");
			params.add(auditStatus);
		}
		
		// 取得总记录行数
		String sql = "select count(1) cnt from t_loan a, t_customer b where a.company_id=? and a.customer_id=b.id and a.auditor_id=?"+where.toString();
		// 列表数据SQL: 把最需要审核的放在前面
		StringBuffer sb = new StringBuffer("");
		if (CommonUtil.getIntValue(reqJson.getString("hidePhone"))>0)
			sb.append("select a.id loanId,REPLACE(b.phone_no, SUBSTR(b.phone_no,4,4), '****') custPhone,b.name custName, a.req_money reqMoney,");
		else
			sb.append("select a.id loanId,b.phone_no custPhone,b.name custName, a.req_money reqMoney,");
		sb.append(" a.start_time startTime, a.end_time endTime, a.req_date reqTime, a.loan_status loanStatus,")
		.append(" (select count(1) from t_loan b where b.customer_id=a.customer_id) loanNum,")
		.append(" (select sum(case when a.late_fee>0 then 1 else 0 end) from t_loan b where b.customer_id=a.customer_id) overTimeNum,")
		.append(" (select count(1) from t_loan_overdue_log b where b.customer_id=a.customer_id) overdueLogNum,")
		.append(" (select u.user_name from t_sys_user u where a.auditor_id=u.id) auditName,a.audit_time auditTime,b.id custId")
		.append(" from t_loan a, t_customer b where a.company_id=? and a.customer_id=b.id and a.auditor_id=?");
		sb.append(where).append(" order by a.id asc");
				
		result.setStatus(0);
		result.setMessage("成功");
		result.setBody(readService.pageQueryBySql(sb.toString(), sql, reqJson.getIntValue("pageSize"), reqJson.getIntValue("pageNo"), params.toArray()));
		return result;
	}
	
	/**
	 * 货款审核
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo loanAudit(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		Long loanId = reqJson.getLong("loanId");
		int auditStatus = CommonUtil.getIntValue(reqJson.getLong("auditStatus"));	
		String auditRemark = reqJson.getString("auditRemark");
		String userId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || loanId == null || loanId < 1 || auditStatus<1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		} 
		String sql = "update t_loan set loan_status=?,audit_time=now(),auditor_id=?,audit_remark=? where company_id=? and loan_status=0 and id=?";
		loanService.executeUpdate(sql, new Object[]{auditStatus,userId,auditRemark,companyId,loanId});
				
		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}
	
	/**
	 * 货款审核员申请货款审核任务
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public ResultInfo reqLoanAudit(HttpServletRequest request, JSONObject reqJson) throws Exception {
		ResultInfo result = new ResultInfo();
		Long companyId = reqJson.getLong("companyId");
		int num = CommonUtil.getIntValue(reqJson.getLong("num"));	
		String userId = reqJson.getString("_currnetUserId");
		
		if(companyId == null || companyId<1 || num < 1) {
			result.setStatus(1);
			result.setMessage("参数错误，请检查！");
			return result;
		} 
		String sql = "update t_loan set auditor_id=? where company_id=? and loan_status=0 and auditor_id is null order by id asc limit ?";
		loanService.executeUpdate(sql, new Object[]{userId,companyId,num});
				
		result.setStatus(0);
		result.setMessage("成功");
		return result;
	}
}
